package main

import (
	"fmt"
	"net"
	"time"

	"bytes"
	"encoding/binary"
)

func intToByte(n int) []byte {
	data := int64(n)
	bytebuffer := bytes.NewBuffer([]byte{})

	binary.Write(bytebuffer, binary.BigEndian, data)

	return bytebuffer.Bytes()
}

func byteToInt(bts []byte) int {

	bytebuffer := bytes.NewBuffer(bts)
	var data int64
	binary.Read(bytebuffer, binary.BigEndian, &data)

	return int(data)
}

func main() {
	tcpaddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:8845")
	if err != nil {
		panic(err)
	}

	conn, err := net.DialTCP("tcp", nil, tcpaddr) //链接
	if err != nil {
		panic(err)
	}

	go ServerMsgHandler(conn)

	arr := []int{1, 9, 2, 82, 7, 13, 5, 66, 10, 4, 23, 24, 1045, 123, 4, 6}
	length := len(arr)

	sendStart := intToByte(0)
	sendStart = append(sendStart, intToByte(0)...)
	conn.Write(sendStart)

	for i := 0; i < length; i++ {

		// fmt.Println(arr[i])

		sendData := intToByte(1)
		sendData = append(sendData, intToByte(arr[i])...)
		conn.Write(sendData)
	}

	sendEnd := intToByte(0)
	sendEnd = append(sendEnd, intToByte(1)...)
	conn.Write(sendEnd)

	time.Sleep(10 * time.Second)

	/**
	for {

		var inputString string
		fmt.Scanln(&inputString)

		conn.Write([]byte(inputString))
		buf := make([]byte, 1024)

		n, _ := conn.Read(buf)
		fmt.Println(string(buf[:n]))

	}
	*/

}

func ServerMsgHandler(conn net.Conn) {
	buf := make([]byte, 16)
	defer conn.Close()
	arr := []int{} //数组保存数据

	for {
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println("client close ")
			break
		} else {
			if n == 16 {
				data1 := byteToInt(buf[:len(buf)/2])
				data2 := byteToInt(buf[len(buf)/2:])

				fmt.Println(data1, data2)

				if data1 == 0 && data2 == 0 {
					arr = make([]int, 0, 0) //开辟数据
				}

				if data1 == 1 {
					arr = append(arr, data2)
				}

				if data1 == 0 && data2 == 1 {

					fmt.Println("数组接受完成", arr)

					arr = make([]int, 0, 0) //开辟数据

				}

			}
		}
	}

}
